package com.simple.framework.core.action.executor;

import com.simple.framework.core.action.Action;
import com.simple.framework.core.action.repository.ActionRepository;
import com.simple.framework.core.entry.ActionContext;
import com.simple.framework.core.entry.ActionResult;
import com.simple.framework.core.exception.ActionException;

/**
 * 默认事件执行器
 * 
 * @author wujiangpo
 *
 * @param <R> 事件结果
 * @param <C> 事件上下文
 */
public class SimpleActionExecutor<R extends ActionResult, C extends ActionContext> implements ActionExecutor<R, C> {

	private ActionRepository<R, C> actionRepository;

	@Override
	public R invoke(Action<R, C> action, C context) throws ActionException {

		if (actionRepository == null) {
			throw new ActionException("事件存储类actionRepository不能为空，请选择事件合适的存储方式。");
		}

		actionRepository.beforeActionProcess(action, context);

		R result = null;

		try {

			result = action.process(context);

		} catch (Exception e) {

			actionRepository.afterActionProcessException(action, context, e);

			throw new ActionException("执行事件异常：", e);
		}
		actionRepository.afterActionProcess(action, context);

		return result;
	}

}
